﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.NetworkInformation;
using System.Text;

namespace Autoupdate
{
	class Program
	{
		static AutoUpdateConfig _config;

		static AutoUpdateConfig _configInServer;

		static bool _isHasNetWork;


		static void Main(string[] args)
		{
			_isHasNetWork = NetHelper.CheckNet();

			if (!_isHasNetWork)
			{
				return; 
			}
			_config = AutoUpdateHelper.GetConfig();
			using (var wc = new System.Net.WebClient())
			{
				var data=wc.DownloadString(new Uri(_config.Url));
				//wc.DownloadStringCompleted += Wc_DownloadStringCompleted;
				CheckVer(data);

			}
			//Console.ReadLine();
		}

		private static void CheckVer(string data) {
			 

			_configInServer = Newtonsoft.Json.JsonConvert.DeserializeObject<AutoUpdateConfig>(data);

			if (_configInServer == null)
			{
				Console.WriteLine("下载失败");
				Console.ReadLine();
			}

			//版本比较
			if (_config.Version != _configInServer.Version)
			{
				//先结束主进程
				var pro = Process.GetProcessesByName(_configInServer.MainExe);//获取已开启的所有进程

				foreach (var item in pro)
				{
					item.Kill();

				}

				//更新配置文件



				var dirInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

				using (var wc = new System.Net.WebClient())
				{
					var regex = new System.Text.RegularExpressions.Regex(@"([^<>/\\\|:""\*\?]+)\.\w+$");
					foreach (var fileUrl in _configInServer.Files)
					{
						var fileName = regex.Match(fileUrl).Value;
						if (System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
						{
							System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + fileName);
						}

						wc.DownloadFile(new Uri(fileUrl), fileName);



						File.Copy(AppDomain.CurrentDomain.BaseDirectory + fileName,

							dirInfo.Parent.FullName + @"\" + fileName, true);
						//wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
					}

				}

				//启动主程序
				ProcessStartInfo processStartInfo = new ProcessStartInfo(dirInfo.Parent.FullName + @"\" + _configInServer.MainExe);

				processStartInfo.WorkingDirectory = dirInfo.Parent.FullName;


				Process.Start(processStartInfo);
			}

		}

		private static void Wc_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
		{
			
		}

		private static void Wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
		{
			
		}

		 
	}
}
